package com.xiangyi.teachingsystem.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiangyi.teachingsystem.dao.LoginLogMapper;
import com.xiangyi.teachingsystem.entity.po.LoginLog;
import com.xiangyi.teachingsystem.entity.po.User;
import com.xiangyi.teachingsystem.entity.vo.Result;
import com.xiangyi.teachingsystem.service.UserService;
import com.xiangyi.teachingsystem.validation.groups.Login;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/admin")
public class AdminLoginController {
    @Autowired
    UserService userService;
    @Autowired
    LoginLogMapper loginLogMapper;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String phoneNum = user.getPhoneNum();
        String passWd = user.getPassWd();
        String jobNum = user.getJobNum();
        User userInfo=null;
        if (phoneNum!=null){
            userInfo = userService.getOne(new QueryWrapper<User>()
                    .eq("phone_num", phoneNum)
                    .eq("admin_sign",true));
        }else if (jobNum!=null){
            userInfo = userService.getOne(new QueryWrapper<User>()
                    .eq("job_num", jobNum)
                    .eq("admin_sign",true));
        }

        if (userInfo!=null){
            if (Objects.equals(userInfo.getPassWd(), passWd)){
                LoginLog loginLog = new LoginLog();
                BeanUtils.copyProperties(user, loginLog);
                loginLog.setUserId(userInfo.getId());
                loginLogMapper.insert(loginLog);
                return Result.success("登录成功").setData(userInfo);
            }
            return Result.failure("密码错误");
        }
        return Result.failure("账号不存在");
    }
}
